package handler

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"user/model"
	"user/utils"

	pb "user/proto"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credential "github.com/aliyun/credentials-go/credentials"
)

type User struct{}

// Description:
//
// 使用凭据初始化账号Client
//
// @return Client
//
// @throws Exception
// 短信
func CreateClient() (_result *openapi.Client, _err error) {
	// 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378661.html。
	credential, _err := credential.NewCredential(nil)
	if _err != nil {
		return _result, _err
	}

	config := &openapi.Config{
		Credential: credential,
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &openapi.Client{}
	_result, _err = openapi.NewClient(config)
	return _result, _err
}

// Description:
//
// # API 相关
//
// @param path - string Path parameters
//
// @return OpenApi.Params
func CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		// 接口名称
		Action: tea.String("SendSms"),
		// 接口版本
		Version: tea.String("2017-05-25"),
		// 接口协议
		Protocol: tea.String("HTTPS"),
		// 接口 HTTP 方法
		Method:   tea.String("POST"),
		AuthType: tea.String("AK"),
		Style:    tea.String("RPC"),
		// 接口 PATH
		Pathname: tea.String("/"),
		// 接口请求体内容格式
		ReqBodyType: tea.String("json"),
		// 接口响应体内容格式
		BodyType: tea.String("json"),
	}
	_result = params
	return _result
}

func (e *User) SendSms(ctx context.Context, req *pb.Request, rsp *pb.Response) error {

	//校验图片验证码
	result := model.CheckImgCode(req.Uuid, req.ImgCode)
	if result {
		//发送短信
		client, _err := CreateClient()
		if _err != nil {
			fmt.Println(_err)
		}

		params := CreateApiInfo()
		// query params
		queries := map[string]interface{}{}
		queries["PhoneNumbers"] = tea.String(req.Phone)
		queries["SignName"] = tea.String("爱家住房网")
		queries["TemplateCode"] = tea.String("SMS_327740793")

		//生成一个随机的六位数验证吗
		rand.Seed(time.Now().UnixNano())
		smsCode := fmt.Sprintf("%06d", rand.Int31n(100000))

		queries["TemplateParam"] = tea.String("{\"code\":\"" + smsCode + "\"}")
		// runtime options
		runtime := &util.RuntimeOptions{}
		request := &openapi.OpenApiRequest{
			Query: openapiutil.Query(queries),
		}
		// 复制代码运行请自行打印 API 的返回值
		// 返回值实际为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
		_, _err = client.CallApi(params, request, runtime)
		if _err != nil {
			//发送失败
			rsp.Errno = utils.RECODE_SMSERR
			rsp.Errmsg = utils.RecodeText(utils.RECODE_SMSERR)
			fmt.Println(_err)
		} else {
			//发送成功
			rsp.Errno = utils.RECODE_OK
			rsp.Errmsg = utils.RecodeText(utils.RECODE_OK)
			fmt.Println("发送验证码成功")
			//将短信验证码存入redis
			err := model.SaveSmsCode(req.Phone, smsCode)
			if err != nil {
				fmt.Println("存储短信验证码失败：", err.Error())
				rsp.Errno = utils.RECODE_DBERR
				rsp.Errmsg = utils.RecodeText(utils.RECODE_DBERR)
			}
		}
	} else {
		//校验失败
		rsp.Errno = utils.RECODE_DATAERR
		rsp.Errmsg = utils.RecodeText(utils.RECODE_DATAERR)
	}
	return nil
}
